//
//  KCXunDianViewController.swift
//  MyKC
//
//  Created by yy on 2017/3/14.
//  Copyright © 2017年 com.yasuo. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel
class KCXunDianViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        getData(inputText: "")
        setupUI()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.subviews[0].alpha = 0
    }
    deinit {
        timer.invalidate()
    }
    
    // MARK: -
    // MARK: - 懒加载基本控件
    lazy var timeView: KCPlanTimeView = {
        let timer = KCPlanTimeView.planTimeView()
        return timer
    }()
    internal var timer: Timer = Timer()
    
    lazy var tableView = UITableView()
    
    lazy var seatchBar: UISearchBar = {
        let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 44))
        searchBar.delegate = self
        searchBar.placeholder = "搜索"
        return searchBar
    }()
    //所有的商店数组
    lazy var allAddStoreArray = [KCAddXunDianStoreModel]()
}
// MARK: -  设置界面基本信息
extension KCXunDianViewController {
    //完成按钮点击事件------
    @objc private func btnFinishClick(sender: UIBarButtonItem) {
        uploadData()
    }
    //定时器---------
    @objc private func timeReapeat() {
        sharedDateFormater.dateFormat = "hh:mm:ss"
        //设置为当前时区
        sharedDateFormater.locale = Locale.current
        timeView.lbe_currentTime.text = sharedDateFormater.string(from: Date.init())
        sharedDateFormater.dateFormat = "yyyy年MM月dd日"
        let dateString = sharedDateFormater.string(from: Date.init())
        sharedDateFormater.dateFormat = "EEEE"
        let stringWeekKey = sharedDateFormater.string(from: Date.init())
        let dic = ["Monday":"星期一","Tuesday":"星期二","Wednesday":"星期三","Thursday":"星期四","Friday":"星期五","Saturday":"星期六","Sunday":"星期日"]
        guard let weekString = dic[stringWeekKey] else {
            return
        }
        timeView.lbe_currentDate.text = dateString + "" + weekString
    }
    
    // MARK: -  设置界面基本信息
    internal func setupUI() {
        title = "新增计划"
        //右侧的按钮
        view.backgroundColor = UIColor.white
        let finishBtnItem = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(btnFinishClick(sender:)))
        navigationItem.rightBarButtonItem = finishBtnItem
        
        //添加timeView
        view.addSubview(timeView)
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timeReapeat), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: .commonModes)
        
        //添加tableVIew
        setupTableView()
    }
    // MARK: -  设置tableView
    private func setupTableView() {
        //设置下面他tableView
        tableView.frame = CGRect(x: 0, y: 157, width: ScreenWidth, height: ScreenHeight - 157)
        view.addSubview(tableView)
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 80
        tableView.tableFooterView = UIView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableHeaderView = seatchBar
        //注册cell
        tableView.register(UINib(nibName: "KCAddStoreCell", bundle: nil), forCellReuseIdentifier: "KCAddStoreCellId")
    }
}

// MARK: -  tableView的代理方法------
extension KCXunDianViewController:UITableViewDataSource,UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allAddStoreArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "KCAddStoreCellId", for: indexPath) as! KCAddStoreCell
        let model = allAddStoreArray[indexPath.row]
        cell.model = model
        return cell
    }
}

// MARK: -  searchBar的代理方法-----
extension KCXunDianViewController: UISearchBarDelegate {
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(true, animated: true)
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(false, animated: true)
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(false, animated: true)
        view.endEditing(true)
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        //输入了数据----根据输入内容进行搜索
        getData(inputText: searchText)
    }
}


// MARK: -  获取网络数据
extension KCXunDianViewController {
    internal func getData(inputText: String) {
        let paraDic = ["TaskPlanTypeCode":"940","StoreName":inputText]
        SVProgressHUD.show()
        KCNetworkManager.sharedTools.request(method: .GET, urlString: "/api/TaskPlan/GetQueryAllStoreList", parameters: paraDic) {[weak self] (response, error) in
            SVProgressHUD.dismiss()
            guard let response = response as? NSDictionary,
                let responseContent = response["Content"] as? NSDictionary,
                let responseAllStoreArray = responseContent["AllStore"] as? NSArray else {
                return
            }
            self?.allAddStoreArray = NSArray.yy_modelArray(with: KCAddXunDianStoreModel.self, json: responseAllStoreArray) as? [KCAddXunDianStoreModel] ?? [KCAddXunDianStoreModel]()
            self?.tableView.reloadData()
        }
    }
}

// MARK: -  提交网络数据
extension KCXunDianViewController {
    internal func uploadData() {
        //搜寻按钮变为正常
        seatchBar.setShowsCancelButton(false, animated: true)
        view.endEditing(true)
        //多个的一般需要
        var tmpArray = [String]()
        for addXunDianStoreModel in allAddStoreArray {
            if addXunDianStoreModel.IsJoinVisit == "1" {
                tmpArray.append(addXunDianStoreModel.StoreId!)
            }
        }
        if tmpArray.count == 0 {
            SVProgressHUD.showError(withStatus: "请先选择门店")
            return
        }
        let paraDic:[String: Any] = ["StoreId":tmpArray,"TaskTypeCode":"940"]
        SVProgressHUD.show()
        KCNetworkManager.sharedTools.request(method: .POST, urlString: "/api/TaskPlan/AddVisitPlan", parameters: paraDic, finished: {[weak self] (response, error) in
            SVProgressHUD.dismiss()
            guard let response = response as? NSDictionary,let msg = response["Msg"] as? String else {
                return
            }
            //显示添加成功----延迟两秒后进行页面跳转
            SVProgressHUD.showSuccess(withStatus: msg)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8, execute: {
                self?.navigationController?.popViewController(animated: true)
            })
        })
    }
}





